import { _decorator, Component, Node, Toggle, UITransform, Label, find, instantiate, resources, TextAsset, Layers, Color, Enum, CCBoolean, CCFloat, Button, EventHandler, sys, v3, log, game } from 'cc';
import { AudioManager } from '../Manager/AudioManager';
import { UIManager } from '../Manager/UIManager';
import { GameManager } from '../Manager/GameManager';

const { ccclass, property } = _decorator;

export enum ContentColor {
    WHITE = 0,
    BLACK = 1
}

Enum(ContentColor);

@ccclass('PrivacyPanel')
export class PrivacyPanel extends Component {

    @property({ type: ContentColor })
    color: ContentColor = ContentColor.BLACK;

    @property(CCFloat)
    trimHeight: number = 2000;

    @property(CCFloat)
    fontSize: number = 20;

    @property(CCBoolean)
    isAlignCenter: boolean = false;

    private _content: Node = null!;
    private _contentUITrans: UITransform = null!;
    private _toggle: Toggle = null!;
    private _privacyStr: string = "";
    private _posY: number = 0;

    onLoad() {
        this._toggle = find("ScrollView/Toggle", this.node).getComponent(Toggle);
        this._content = find("ScrollView/view/content", this.node);
        this._contentUITrans = this._content.getComponent(UITransform);

        resources.load("Datas/Privacy", TextAsset, (err, res) => {
            if (err) return;
            this._privacyStr = res.text;

            this.TruncateString(this.trimHeight);

            this._contentUITrans.setContentSize(this._contentUITrans.contentSize.width, Math.abs(this._posY) + 300);
        });

        //按钮
        let button = find("ScrollView/Button", this.node).getComponent(Button);
        const clickEventHandler = new EventHandler();
        clickEventHandler.target = this.node; // 这个 node 节点是你的事件处理代码组件所属的节点
        clickEventHandler.component = 'PrivacyPanel';// 这个是脚本类名
        clickEventHandler.handler = 'OnButtonClick';
        clickEventHandler.customEventData = '';
        button.clickEvents.push(clickEventHandler);

        if (GameManager.Instance.GetLocalStorage("首次登录") == "0") {
            this.Show(true);
        }
        else {
            this.Show(false);
        }
    }

    TruncateString(maxLength: number): string {
        let len = 0;
        let index = 0;

        while (index < this._privacyStr.length) {
            const char = this._privacyStr.charAt(index);

            char.charCodeAt(0) > 255 ? len += 2 : len += 1; // 如果是中文字符，长度加2

            if (len > maxLength) {
                let str = this._privacyStr.substring(0, index);

                this.CreateLabel(str);

                this._privacyStr = this._privacyStr.substring(index, this._privacyStr.length)

                this.TruncateString(maxLength);

                return;
            }

            if (this._privacyStr.length <= maxLength) {
                this.CreateLabel(this._privacyStr);
                return;
            }

            index++;
        }

    }

    CreateLabel(str: string) {
        //生成
        let newNode = new Node();
        let nd = instantiate(newNode);
        nd.layer = Layers.Enum.UI_2D;
        this._content.addChild(nd);

        //位置
        nd.addComponent(UITransform).anchorPoint.set(0.5, 1);
        nd.getComponent(UITransform).contentSize.set(this._contentUITrans.contentSize.width, 0);
        nd.position.set(0, this._posY, 0);

        //赋值
        let lb = nd.addComponent(Label);
        lb.verticalAlign = Label.VerticalAlign.TOP;
        lb.horizontalAlign = this.isAlignCenter ? Label.HorizontalAlign.CENTER : Label.HorizontalAlign.LEFT;
        lb.overflow = Label.Overflow.RESIZE_HEIGHT;
        switch (this.color) {
            case ContentColor.BLACK:
                lb.color = Color.BLACK;
                break;
            case ContentColor.WHITE:
                lb.color = Color.WHITE;
                break;
            default:
                lb.color = Color.BLACK;
                break;
        }

        lb.fontSize = this.fontSize;
        lb.lineHeight = this.fontSize + this.fontSize / 5;
        lb.string = str;
        lb.updateRenderData(true);

        let height = nd.getComponent(UITransform).contentSize.height;
        if (height >= 2048) {
            console.error("隐私有文本高于2048，需要检查");
        }

        this._posY -= height;
    }

    Show(active: boolean = true) {
        this.node.active = active;
    }

    OnButtonClick() {
        AudioManager.Instance.playSound("Audio/Button");
        if (this._toggle.isChecked) {
            if (GameManager.Instance.GetLocalStorage("首次登录") == "0") {
                GameManager.Instance.SetLocalStorage("首次登录", "1");
            }
            this.Show(false);
        } else {
            UIManager.Instance.ShowTipLabelByString("您需要先勾选同意隐私政策。", v3(0, 600));
        }
    }

}
